package crm8000.services

import crm8000.Models.Warehouse;
import crm8000.Models.WarehouseCodeHelp
import crm8000.helper.PinYinHelper
import crm8000.helper.Result
import grails.transaction.Transactional

@Transactional
class WarehouseService {

	def warehouseList() {
		return Warehouse.listOrderByCode()
	}

	Result editWarehouse(params) {
		if (params.id) {
			// 编辑
			def c = Warehouse.countByCodeAndIdNotEqual(params.code, params.id)
			if (c > 0) {
				return new Result(success: false, msg: "编码为${params.code}的仓库已经存在")
			}

			def warehouse = Warehouse.get(params.id)
			warehouse.code = params.code
			warehouse.name = params.name
			warehouse.save()
			
			// 处理拼音字头
			def py = WarehouseCodeHelp.findAllByWarehouseId(warehouse.id)
			py*.delete()
			def hcList = new PinYinHelper().toPinYin(warehouse.name)
			for (hc in hcList) {
				new WarehouseCodeHelp(warehouseId: warehouse.id, codeHelp: hc.toUpperCase()).save()
			}

			return new Result(success: true, id: warehouse.id)
		} else {
			// 新增
			def c = Warehouse.countByCode(params.code)
			if (c > 0) {
				return new Result(success: false, msg: "编码为${params.code}的仓库已经存在")
			}

			def warehouse = new Warehouse(code: params.code, name: params.name, inited: false)
			warehouse.save()
			
			// 处理拼音字头
			def hcList = new PinYinHelper().toPinYin(warehouse.name)
			for (hc in hcList) {
				new WarehouseCodeHelp(warehouseId: warehouse.id, codeHelp: hc.toUpperCase()).save()
			}

			return new Result(success: true, id: warehouse.id)
		}
	}

	Result deleteWarehouse(String id) {
		def warehouse = Warehouse.get(id)
		if (!warehouse) {
			return new Result(success: false, msg: "仓库不存在")
		}
		
		// TODO 需要盘点仓库是否能删除
		warehouse.delete()
		// 处理拼音字头
		def py = WarehouseCodeHelp.findAllByWarehouseId(id)
		py*.delete()

		return new Result(success: true)
	}
	
	def queryData(String queryKey) {
		if (!queryKey) {
			return []
		}
		queryKey += "%";
		def idList = []
		WarehouseCodeHelp.findAllByCodeHelpIlike(queryKey).each {
			idList.add(it.warehouseId)
		}

		return Warehouse.createCriteria().list  {
			or {
				if (idList.size() > 0) {
					'in' ("id", idList)
				}
				or {
					ilike("code", queryKey)
					ilike("name", queryKey)
				}}
			order "code"
			maxResults 20
		}
	}
}
